const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const index = require('./routes/index')
const users = require('./routes/users')
//const log= require('./middleware/log4j')
const cors = require('koa-cors');

const schedule = require('node-schedule');
const moment = require('moment');

// 使用koa-cors
app.use(cors());

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())

app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  //console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
  //var ip = ctx.request.header('x-forwarded-for') || ctx.request.connection.remoteAddress
  //log.info(`访问来IP： ${ctx.method} ${ctx.url} - ${ms}ms`)
})



// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(async(ctx,next)=>{
  if(ctx.request.url=='/favicon.ico') {
    return
  }else{
    next();
  }
});


// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});
// app.listen(9090,()=>{
//   console.log("APP listen 9090");
// })

//https://www.npmjs.com/package/node-schedule  秒 分钟、小时
// second (0-59)
// minute (0-59)
// hour (0-23)
// date (1-31)
// month (0-11)
// year
// dayOfWeek (0-6) Starting with Sunday
 //时间格式为 ‘42 12 * * 5’  或者 ‘0 42 12 * * 5’，
var j = schedule.scheduleJob(' 0 0 11 * * *', function(){
  let time= new Date();
  console.log(moment(time).format('YYYY-MM-DD HH:mm:ss'));
});

module.exports = app


